package com.aliyun.oss;


import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

public class AliYunUtil {
//    @Value("${aliyun.oss.endpoint}")
//    public static String endpoint;
//    @Value("aliyun.oss.accessKeyId")
//    public static String accessKeyId;
//    @Value("aliyun.oss.accessKeySecret")
//    public static String accessKeySecret;
//    @Value("aliyun.oss.bucketName")
//    public static String bucketName;
    private AliYun aliYun;

    public AliYun getAliYun() {
        return aliYun;
    }

    public void setAliYun(AliYun aliYun) {
        this.aliYun = aliYun;
    }

    public String upload(MultipartFile file) throws Exception {
        String endpoint = aliYun.getEndpoint();
        String accessKeyId = aliYun.getAccessKeyId();
        String bucketName = aliYun.getBucketName();
        String accessKeySecret = aliYun.getAccessKeySecret();


        InputStream inputStream = file.getInputStream();

        String originalFilename = file.getOriginalFilename();
        String objectName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf('.'));


        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, objectName, inputStream);

        //  拼接返回的路径
        String  url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + objectName;
        // 关闭
        ossClient.shutdown();
        return url;
    }
}
